<?php

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Utils\ApplicationContext;
use NanQi\Hope\App;
use NanQi\Hope\Constants\ErrorCodeConstants;
use NanQi\Hope\Constants\StatusCodeConstants;
use NanQi\Hope\Exception\BusinessException;
use Psr\Container\ContainerInterface;
use Symfony\Component\VarDumper\VarDumper;

if (!function_exists('di')) {
    /**
     * 获取依赖注入对象
     * @param string $id
     * @return mixed Entry.
     */
    function di(string $id) {
        return ApplicationContext::getContainer()->get($id);
    }
}

if (!function_exists('dump')) {
    /**
     * @author Nicolas Grekas <p@tchwork.com>
     */
    function dump($var, ...$moreVars)
    {
        VarDumper::dump($var);

        foreach ($moreVars as $v) {
            VarDumper::dump($v);
        }

        if (1 < func_num_args()) {
            return func_get_args();
        }

        return $var;
    }
}

if (!function_exists('dd')) {
    function dd(...$vars)
    {
        foreach ($vars as $v) {
            VarDumper::dump($v);
        }

        throw new BusinessException(999, '调试中');
    }
}


if (!function_exists('app')) {
    function app() : App
    {
        /** @var App $app */
        $app = di(App::class);
        return $app;
    }
}

if (! function_exists('abort')) {

    function abort($errorCode, $errorMessage = '')
    {
        /** @var ContainerInterface $container */
        $container = di(ContainerInterface::class);

        if ($container->has(ErrorCodeConstants::class)) {
            /** @var ErrorCodeConstants $errorCodeConstants */
            $errorCodeConstants = di(ErrorCodeConstants::class);
            if (!$errorMessage && $errorCodeConstants) {
                $errorMessage = $errorCodeConstants::getMessage($errorCode);
            }
        } else {
            $errorMessage = 'none';
        }

        throw new BusinessException(StatusCodeConstants::S_400_BAD_REQUEST,
            $errorMessage, $errorCode);
    }
}

if (! function_exists('abort_if')) {

    function abort_if($boolean, $code, $message = '')
    {
        if ($boolean) {
            abort($code, $message);
        }
    }
}

if (! function_exists('abort_unless')) {

    function abort_unless($boolean, $code, $message = '')
    {
        if (! $boolean) {
            abort($code, $message);
        }
    }
}

if (! function_exists('info')) {

    function info($message, $context = [])
    {
        /** @var StdoutLoggerInterface $logger */
        $logger = di(StdoutLoggerInterface::class);
        $logger->info($message, $context);
    }
}

if (! function_exists('now')) {

    function now($tz = null)
    {
        return \Carbon\Carbon::now($tz);
    }
}


if (! function_exists('today')) {

    function today($tz = null)
    {
        return \Carbon\Carbon::today($tz);
    }
}